package com.syt.dome.service.impl;

import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.syt.commer.ResultCodeEnum;
import com.syt.commer.excption.YyghException;
import com.syt.common.utlis.TimeUtil;
import com.syt.dome.mapper.ScheduleMapper;
import com.syt.dome.repository.ScheduleRepository;
import com.syt.dome.service.DepartmentService;
import com.syt.dome.service.HospitalService;
import com.syt.dome.service.ScheduleService;
import com.syt.entity.model.hosp.BookingRule;
import com.syt.entity.model.hosp.Department;
import com.syt.entity.model.hosp.Hospital;
import com.syt.entity.model.hosp.Schedule;
import com.syt.entity.vo.hosp.BookingScheduleRuleVo;
import com.syt.entity.vo.hosp.ScheduleOrderVo;
import com.syt.entity.vo.hosp.ScheduleQueryVo;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;

import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.util.CloseableIterator;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ScheduleServiceImpl extends
        ServiceImpl<ScheduleMapper, Schedule> implements ScheduleService {


    @Autowired
    private ScheduleRepository scheduleRepository;


    @Autowired
    private MongoTemplate mongoTemplate;// 用来做聚合

    @Autowired
    private HospitalService hospitalService;

    @Autowired
    private DepartmentService departmentService;


    /**
     * 修改排班, 用于 mq的操作  更新排班信息
     */

    @Override
    public void update(Schedule schedule) {
        schedule.setUpdateTime(new Date());
        //主键一致就是更新
        scheduleRepository.save(schedule);
    }


    ////获取排班id获取排班数据
//    @Override
//    public Schedule getScheduleId(String scheduleId) {
//        Schedule schedule = scheduleRepository.findById(scheduleId).get();
//       return this.packageSchedule(schedule);
////        return schedule;
//    }
    ////获取排班id获取排班数据
    @Override
    public Schedule getScheduleId(String scheduleId) {
        Schedule schedule = scheduleRepository.findById(scheduleId).get();
        return this.packageSchedule(schedule);
    }
    //据排班id获取排班数据

    @Override
    public Schedule getScheduleById(String scheduleId) {
        Optional<Schedule> scheduleOptional = scheduleRepository.findById(scheduleId);
        if (scheduleOptional.isPresent()) {
            Schedule schedule = scheduleOptional.get();
            this.setSchedule(schedule);
            return schedule;
        } else {
            return new Schedule();
        }
    }

    /**
     * 封装排班详情其他值 医院名称、科室名称、日期对应星期
     *
     * @param: [item]
     * @return: void
     */
    private void setSchedule(Schedule schedule) {
        //设置医院名称
        schedule.getParam().put("hosname", hospitalService.getByHoscode(schedule.getHoscode()).getHosname());
        //设置科室名称
        schedule.getParam().put("depname", hospitalService.getDepartment(schedule.getHoscode(), schedule.getDepcode()).getDepname());
        //设置日期对应星期
        schedule.getParam().put("dayOfWeek", this.getDayOfWeek(new DateTime(schedule.getWorkDate())));
    }


//    @Override
//    public Schedule getScheduleById(String scheduleId) {
//        Optional<Schedule> scheduleOptional = scheduleRepository.findById(scheduleId);
//        if(scheduleOptional.isPresent()){
//            Schedule schedule = scheduleOptional.get();
//            this.setSchedule(schedule);
//            return schedule;
//        }else{
//            return new Schedule();
//        }
//    }


    //根据排班id获取预约下单数据
    @Override
    public ScheduleOrderVo getScheduleOrderVo(String scheduleId) {

        //排班信息
//        Schedule schedule = baseMapper.selectById(scheduleId);
//        Optional<Schedule> scheduleOptional = scheduleRepository.findById(scheduleId);
        Schedule schedule = this.getScheduleById(scheduleId);
        System.out.println("6*62111*616*4*4*4*46*46*46*46*46*4" + schedule);

        if (schedule==null) {
            throw new YyghException(ResultCodeEnum.DATA_ERROR);

        }


//        Optional<Schedule> scheduleOptional = scheduleRepository.findById(scheduleId);
//        if (!scheduleOptional.isPresent()){
//            throw new YyghException(ResultCodeEnum.DATA_ERROR);
//        }


        //获取预约规则信息

        Hospital hospital = hospitalService.getByHoscode(schedule.getHoscode());
        if (hospital == null) {
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        System.out.println("..........."+hospital);
        BookingRule bookingRule = hospital.getBookingRule();
        if (bookingRule == null) {
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        System.out.println("./,/,/,/.,/"+bookingRule);


// 把获取到数据 设置到    scheduleOrderVo 里面去
        ScheduleOrderVo scheduleOrderVo = new ScheduleOrderVo();
        scheduleOrderVo.setHoscode(schedule.getHoscode());
        scheduleOrderVo.setHosname(hospitalService.getHospName(schedule.getHoscode()));
        scheduleOrderVo.setDepcode(schedule.getDepcode());
        scheduleOrderVo.setDepname(departmentService.getDepName(schedule.getHoscode(), schedule.getDepcode()));
//.......................................
        scheduleOrderVo.setHosScheduleId(schedule.getHosScheduleId());
//        ........................
        scheduleOrderVo.setAvailableNumber(schedule.getAvailableNumber());
        scheduleOrderVo.setTitle(schedule.getTitle());
        scheduleOrderVo.setReserveDate(schedule.getWorkDate());
        scheduleOrderVo.setReserveTime(schedule.getWorkTime());
        scheduleOrderVo.setAmount(schedule.getAmount());


//        //把获取数据设置到scheduleOrderVo
System.out.println("dsvfrsdv"+scheduleOrderVo);

        //退号截止天数（如：就诊前一天为-1，当天为0）
        Integer quitDay = bookingRule.getQuitDay();
        DateTime quitTime = this.getDateTime(new DateTime(schedule.getWorkDate()).plusDays(quitDay).toDate(), bookingRule.getQuitTime());
        scheduleOrderVo.setQuitTime(quitTime.toDate());


        //预约开始时间
        DateTime startTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        scheduleOrderVo.setStartTime(startTime.toDate());

        //预约截止时间
        DateTime endTime = this.getDateTime(new DateTime().plusDays(bookingRule.getCycle()).toDate(), bookingRule.getStopTime());
        scheduleOrderVo.setEndTime(endTime.toDate());

        //当天停止挂号时间
        DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
        scheduleOrderVo.setStartTime(startTime.toDate());

System.out.println("000000"+scheduleOrderVo);
        return scheduleOrderVo;
    }


//*-*--*-/-/-*/
//@Override
//public ScheduleOrderVo getScheduleOrderVo(String scheduleId) {
//    Optional<Schedule> scheduleOptional = scheduleRepository.findById(scheduleId);
//    if (!scheduleOptional.isPresent()){
//        throw new YyghException(ResultCodeEnum.DATA_ERROR);
//    }
//
//    //获取预约规则信息
//    Schedule schedule = scheduleOptional.get();
//    Hospital hospital = hospitalService.getByHoscode(schedule.getHoscode());
//    if(hospital == null){
//        throw new YyghException(ResultCodeEnum.DATA_ERROR);
//    }
//    BookingRule bookingRule = hospital.getBookingRule();
//    if(bookingRule == null){
//        throw new YyghException(ResultCodeEnum.DATA_ERROR);
//    }
//    ScheduleOrderVo scheduleOrderVo = new ScheduleOrderVo();
//    scheduleOrderVo.setHoscode(schedule.getHoscode());
//    scheduleOrderVo.setHosname(hospital.getHosname());
//    scheduleOrderVo.setDepcode(schedule.getDepcode());
//    scheduleOrderVo.setDepname(departmentService.getDepartment(schedule.getHoscode(), schedule.getDepcode()).getDepname());
//    scheduleOrderVo.setHosScheduleId(schedule.getHosScheduleId());
//    scheduleOrderVo.setAvailableNumber(schedule.getAvailableNumber());
//    scheduleOrderVo.setTitle(schedule.getTitle());
//    scheduleOrderVo.setReserveDate(schedule.getWorkDate());
//    scheduleOrderVo.setReserveTime(schedule.getWorkTime());
//    scheduleOrderVo.setAmount(schedule.getAmount());
//
//    //退号截止天数（如：就诊前一天为-1，当天为0）
//    Integer quitDay = bookingRule.getQuitDay();
//    DateTime quitDateTime = TimeUtil.getDateTime(new DateTime(schedule.getWorkDate()).plus(quitDay).toDate(), bookingRule.getQuitTime());
//    scheduleOrderVo.setQuitTime(quitDateTime.toDate());
//
//    //预约开始时间
//    DateTime startDateTime = TimeUtil.getDateTime(new Date(), bookingRule.getReleaseTime());
//    scheduleOrderVo.setStartTime(startDateTime.toDate());
//
//    //预约截止时间
//    DateTime endDateTime = TimeUtil.getDateTime(new DateTime().plusDays(bookingRule.getCycle()).toDate(), bookingRule.getStopTime());
//    scheduleOrderVo.setEndTime(endDateTime.toDate());
//
//    //当天停止挂号时间
//    DateTime stopDateTime = TimeUtil.getDateTime(new Date(), bookingRule.getStopTime());
//    scheduleOrderVo.setStopTime(stopDateTime.toDate());
//
//    return scheduleOrderVo;
//}
//    -*-/-/-**-/


    //    @Override
//    public Map<String, Object> getBookingScheduleRule(int page, int limit, String hoscode, String depcode) {
//        Map<String, Object> result = new HashMap<>();
//
//        //获取预约规则
//        Hospital hospital = hospitalService.getByHoscode(hoscode);
//        if(null == hospital) {
//            throw new YyghException(ResultCodeEnum.DATA_ERROR);
//        }
//        BookingRule bookingRule = hospital.getBookingRule();
//
//        //获取可预约日期分页数据
//        IPage iPage = this.getListDate(page, limit, bookingRule);
//        //当前页可预约日期
//        List<Date> dateList = iPage.getRecords();
//        //获取可预约日期科室剩余预约数
//        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode).and("workDate").in(dateList);
//        Aggregation agg = Aggregation.newAggregation(
//                Aggregation.match(criteria),
//                Aggregation.group("workDate")//分组字段
//                        .first("workDate").as("workDate")
//                        .count().as("docCount")
//                        .sum("availableNumber").as("availableNumber")
//                        .sum("reservedNumber").as("reservedNumber")
//        );
//        AggregationResults<BookingScheduleRuleVo> aggregationResults = mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);
//        List<BookingScheduleRuleVo> scheduleVoList = aggregationResults.getMappedResults();
//        //获取科室剩余预约数
//
//        //合并数据 将统计数据ScheduleVo根据“安排日期”合并到BookingRuleVo
//        Map<Date, BookingScheduleRuleVo> scheduleVoMap = new HashMap<>();
//        if(!CollectionUtils.isEmpty(scheduleVoList)) {
//            scheduleVoMap = scheduleVoList.stream().collect(Collectors.toMap(BookingScheduleRuleVo::getWorkDate, BookingScheduleRuleVo -> BookingScheduleRuleVo));
//        }
//        //获取可预约排班规则
//        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = new ArrayList<>();
//        for(int i=0, len=dateList.size(); i<len; i++) {
//            Date date = dateList.get(i);
//
//            BookingScheduleRuleVo bookingScheduleRuleVo = scheduleVoMap.get(date);
//            if(null == bookingScheduleRuleVo) { // 说明当天没有排班医生
//                bookingScheduleRuleVo = new BookingScheduleRuleVo();
//                //就诊医生人数
//                bookingScheduleRuleVo.setDocCount(0);
//                //科室剩余预约数  -1表示无号
//                bookingScheduleRuleVo.setAvailableNumber(-1);
//            }
//            bookingScheduleRuleVo.setWorkDate(date);
//            bookingScheduleRuleVo.setWorkDateMd(date);
//            //计算当前预约日期为周几
//            String dayOfWeek = this.getDayOfWeek(new DateTime(date));
//            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);
//
//            //最后一页最后一条记录为即将预约   状态 0：正常 1：即将放号 -1：当天已停止挂号
//            if(i == len-1 && page == iPage.getPages()) {
//                bookingScheduleRuleVo.setStatus(1);
//            } else {
//                bookingScheduleRuleVo.setStatus(0);
//            }
//            //当天预约如果过了停号时间， 不能预约
//            if(i == 0 && page == 1) {
//                DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
//                if(stopTime.isBeforeNow()) {
//                    //停止预约
//                    bookingScheduleRuleVo.setStatus(-1);
//                }
//            }
//            bookingScheduleRuleVoList.add(bookingScheduleRuleVo);
//        }
//
//        //可预约日期规则数据
//        result.put("bookingScheduleList", bookingScheduleRuleVoList);
//        result.put("total", iPage.getTotal());
//        //其他基础数据
//        Map<String, String> baseMap = new HashMap<>();
//        //医院名称
//        baseMap.put("hosname", hospitalService.getHospName(hoscode));
//        //科室
//        Department department =departmentService.getDepartment(hoscode, depcode);
//        //大科室名称
//        baseMap.put("bigname", department.getBigname());
//        //科室名称
//        baseMap.put("depname", department.getDepname());
////月
//        baseMap.put("workDateString", new DateTime().toString("yyyy年MM月"));
////放号时间
//        baseMap.put("releaseTime", bookingRule.getReleaseTime());
////停号时间
//        baseMap.put("stopTime", bookingRule.getStopTime());
//        result.put("baseMap", baseMap);
//        return result;
//    }
//    /**
//     * 获取可预约日期分页数据
//     */
//    private IPage<Date> getListDate(int page, int limit, BookingRule bookingRule) {
////当天放号时间
//        DateTime releaseTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
////预约周期
//        int cycle = bookingRule.getCycle();
////如果当天放号时间已过，则预约周期后一天为即将放号时间，周期加1
//        if(releaseTime.isBeforeNow()) cycle += 1;
////可预约所有日期，最后一天显示即将放号倒计时
//        List<Date> dateList = new ArrayList<>();
//        for (int i = 0; i < cycle; i++) {
////计算当前预约日期
//            DateTime curDateTime = new DateTime().plusDays(i);
//            String dateString = curDateTime.toString("yyyy-MM-dd");
//            dateList.add(new DateTime(dateString).toDate());
//        }
////日期分页，由于预约周期不一样，页面一排最多显示7天数据，多了就要分页显示
//        List<Date> pageDateList = new ArrayList<>();
//        int start = (page-1)*limit;
//        int end = (page-1)*limit+limit;
//        if(end >dateList.size()) end = dateList.size();
//        for (int i = start; i < end; i++) {
//            pageDateList.add(dateList.get(i));
//        }
//        IPage<Date> iPage = new com.baomidou.mybatisplus.extension.plugins.pagination.Page(page, 7, dateList.size());
//        iPage.setRecords(pageDateList);
//        return iPage;
//    }
//    /**
//     * 将Date日期（yyyy-MM-dd HH:mm）转换为DateTime
//     */
//    private DateTime getDateTime(Date date, String timeString) {
//        String dateTimeString = new DateTime(date).toString("yyyy-MM-dd") + " "+ timeString;
//        DateTime dateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(dateTimeString);
//        return dateTime;
//    }
    @Override// 获取可预约的排班数据
    public Map<String, Object> getBookingScheduleRule(int page, int limit, String hoscode, String depcode) {
        Map<String, Object> result = new HashMap<>();

        //获取预约规则
//        根据医院的编号获取预约规则
        Hospital hospital = hospitalService.getByHoscode(hoscode);
        if (null == hospital) {
            throw new YyghException(ResultCodeEnum.DATA_ERROR);
        }
        BookingRule bookingRule = hospital.getBookingRule();


        //获取可预约日期分页数据（分页显示）
        IPage iPage = this.getListDate(page, limit, bookingRule);
        //当前页可预约日期
        List<Date> dateList = iPage.getRecords();

        //获取可预约日期科室剩余预约数
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode).and("workDate").in(dateList);
        Aggregation agg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")//分组字段
                        .first("workDate").as("workDate")
                        .count().as("docCount")
                        .sum("availableNumber").as("availableNumber")
                        .sum("reservedNumber").as("reservedNumber")
        );
        AggregationResults<BookingScheduleRuleVo> aggregationResults = mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> scheduleVoList = aggregationResults.getMappedResults();
        //获取科室剩余预约数

        //合并数据 将统计数据ScheduleVo根据“安排日期”合并到BookingRuleVo
        Map<Date, BookingScheduleRuleVo> scheduleVoMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(scheduleVoList)) {
            scheduleVoMap = scheduleVoList.stream().
                    collect(
                            Collectors.toMap(BookingScheduleRuleVo::getWorkDate,
                                    BookingScheduleRuleVo -> BookingScheduleRuleVo));
        }

        //获取可预约排班规则
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = new ArrayList<>();
        for (int i = 0, len = dateList.size(); i < len; i++) {
            Date date = dateList.get(i);
// 从map集合根据key日期获取value值
            BookingScheduleRuleVo bookingScheduleRuleVo = scheduleVoMap.get(date);
//            如果说当天没有排班医生做一个设置6353333333333333333
            if (null == bookingScheduleRuleVo) { // 说明当天没有排班医生
                bookingScheduleRuleVo = new BookingScheduleRuleVo();
                //就诊医生人数
                bookingScheduleRuleVo.setDocCount(0);
                //科室剩余预约数  -1表示无号
                bookingScheduleRuleVo.setAvailableNumber(-1);
            }
            bookingScheduleRuleVo.setWorkDate(date);
            bookingScheduleRuleVo.setWorkDateMd(date);
            //计算当前预约日期为周几
            String dayOfWeek = this.getDayOfWeek(new DateTime(date));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);

            //最后一页最后一条记录为即将预约   状态 0：正常 1：即将放号 -1：当天已停止挂号
            if (i == len - 1 && page == iPage.getPages()) {
                bookingScheduleRuleVo.setStatus(1);
            } else {
                bookingScheduleRuleVo.setStatus(0);
            }
            //当天预约如果过了停号时间， 不能预约
            if (i == 0 && page == 1) {
                DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
                if (stopTime.isBeforeNow()) {
                    //停止预约
                    bookingScheduleRuleVo.setStatus(-1);
                }
            }
            bookingScheduleRuleVoList.add(bookingScheduleRuleVo);
        }

        //可预约日期规则数据
        result.put("bookingScheduleList", bookingScheduleRuleVoList);
        result.put("total", iPage.getTotal());
        //其他基础数据
        Map<String, String> baseMap = new HashMap<>();
        //医院名称
        baseMap.put("hosname", hospitalService.getHospName(hoscode));
        //科室
        Department department = departmentService.getDepartment(hoscode, depcode);
        //大科室名称
        baseMap.put("bigname", department.getBigname());
        //科室名称
        baseMap.put("depname", department.getDepname());
//月
        baseMap.put("workDateString", new DateTime().toString("yyyy年MM月"));
//放号时间
        baseMap.put("releaseTime", bookingRule.getReleaseTime());
//停号时间
        baseMap.put("stopTime", bookingRule.getStopTime());
        result.put("baseMap", baseMap);
        return result;
    }

    /**
     * 获取可预约日期分页数据
     */
    private IPage<Date> getListDate(int page, int limit, BookingRule bookingRule) {
//当天放号时间
        DateTime releaseTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
//预约周期
        int cycle = bookingRule.getCycle();
        //如果当天放号时间已过，则预约周期后一天为即将放号时间，周期加1
        if (releaseTime.isBeforeNow()) {
            cycle += 1;
        }
        //可预约所有日期，最后一天显示即将放号倒计时
        List<Date> dateList = new ArrayList<>();
        for (int i = 0; i < cycle; i++) {
            //计算当前预约日期
            DateTime curDateTime = new DateTime().plusDays(i);
            String dateString = curDateTime.toString("yyyy-MM-dd");
            dateList.add(new DateTime(dateString).toDate());
        }
        //日期分页，由于预约周期不一样，页面一排最多显示7天数据，多了就要分页显示
        List<Date> pageDateList = new ArrayList<>();
        int start = (page - 1) * limit;
        int end = (page - 1) * limit + limit;
        // 如果可以显示的数据小于七，直接显示
        if (end > dateList.size()) {
            end = dateList.size();
        }
        for (int i = start; i < end; i++) {
            pageDateList.add(dateList.get(i));
        }
        //如果可以显示的数据大于七，进行分页
        IPage<Date> iPage = new com.baomidou.mybatisplus.extension.plugins.pagination.Page(page, 7, dateList.size());
        iPage.setRecords(pageDateList);
        return iPage;
    }

    /**
     * 将Date日期（yyyy-MM-dd HH:mm）转换为DateTime
     *
     * @param date
     * @param timeString
     * @return
     */
    private DateTime getDateTime(Date date, String timeString) {
        String dateTimeString = new DateTime(date).toString("yyyy-MM-dd") + " " + timeString;
        DateTime dateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(dateTimeString);
        return dateTime;
    }


    //    根据医院编号，科室编号和工作日期，查询排班详情信息
    @Override
    public List<Schedule> getDetailSchedule(String hoscode, String depcode, String workDate) {
        //根据参数查询mongodb
        List<Schedule> scheduleList =
                scheduleRepository.findScheduleByHoscodeAndDepcodeAndWorkDate(hoscode, depcode, new DateTime(workDate).toDate());

        //把得到list集合遍历，向设置其他值：医院名称、科室名称、日期对应星期
        scheduleList.stream().forEach(item -> {
            this.packageSchedule(item);
        });


        return scheduleList;
    }

    //封装排班详情其他值 医院名称、科室名称、日期对应星期
    private Schedule packageSchedule(Schedule schedule) {
        // 设置医院名称
        schedule.getParam().put("hosname", hospitalService.getHospName(schedule.getHoscode()));
        //设置科室名称
        schedule.getParam().put("depname", departmentService.getDepName(schedule.getHoscode(), schedule.getDepcode()));
        //设置日期对应星期
        schedule.getParam().put("dayOfWeek", this.getDayOfWeek(new DateTime(schedule.getWorkDate())));

        return schedule;
    }
   /* //封装排班详情其他值 医院名称、科室名称、日期对应星期
    private void packageSchedule(Schedule schedule) {
        //设置医院名称
        schedule.getParam().put("hosname",hospitalService.getHospName(schedule.getHoscode()));
        //设置科室名称
        schedule.getParam().put("depname",departmentService.getDepName(schedule.getHoscode(),schedule.getDepcode()));
        //设置日期对应星期
        schedule.getParam().put("dayOfWeek",this.getDayOfWeek(new DateTime(schedule.getWorkDate())));
    }*/


    // // 根据医院编号 和科室编号 查询排班的规则数据
    @Override
    public Map<String, Object> getRuleSchedule(long page, long limit, String hoscode, String depcode) {

        // 根据医院编号 和科室编号 查询
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode);// 条件的封装
//        根据工作日 workDate 日期进行分组
        Aggregation agg = Aggregation.newAggregation(
                // 分组
                Aggregation.match(criteria),// 匹配条件
                Aggregation.group("workDate")// 分组字段
                        .first("workDate").as("workDate")
                        // 统计号源数量
                        .count().as("docCount")
                        .sum("reservedNumber").as("reservedNumber")
                        .sum("availableNumber").as("availableNumber"),
                //排序
                Aggregation.sort(Sort.Direction.DESC, "workDate"),
                // 实现分页
                Aggregation.skip((page - 1) * limit),
                Aggregation.limit(limit)

        );
        // 调用方法最终执行
        AggregationResults<BookingScheduleRuleVo> aggregates = mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = aggregates.getMappedResults();


//        实现分页, 分组查询之后总的记录数
        Aggregation totalAgg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")
        );

        AggregationResults<BookingScheduleRuleVo> totalAggResults =
                mongoTemplate.aggregate(totalAgg,
                        Schedule.class, BookingScheduleRuleVo.class);
        int total = totalAggResults.getMappedResults().size();

        // 把日期对应的星期 对应获取
        for (BookingScheduleRuleVo bookingScheduleRuleVo : bookingScheduleRuleVoList) {

            // 通过日期获得星期
            Date workDate = bookingScheduleRuleVo.getWorkDate();

            String dayOfWeek = this.getDayOfWeek(new DateTime(workDate));

            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);


        }

        // 设置最终数据，进行返回
        //设置最终数据，进行返回
        Map<String, Object> result = new HashMap<>();
        result.put("bookingScheduleRuleList", bookingScheduleRuleVoList);
        result.put("total", total);

        //获取医院名称
        String hosName = hospitalService.getHospName(hoscode);
        //其他基础数据
        Map<String, String> baseMap = new HashMap<>();
        baseMap.put("hosname", hosName);
        result.put("baseMap", baseMap);

        return result;

    }


// 日期工具类

    /**
     * 根据日期获取周几数据
     *
     * @param dateTime
     * @return
     */
    private String getDayOfWeek(DateTime dateTime) {
        String dayOfWeek = "";
        switch (dateTime.getDayOfWeek()) {
            case DateTimeConstants.SUNDAY:
                dayOfWeek = "周日";
                break;
            case DateTimeConstants.MONDAY:
                dayOfWeek = "周一";
                break;
            case DateTimeConstants.TUESDAY:
                dayOfWeek = "周二";
                break;
            case DateTimeConstants.WEDNESDAY:
                dayOfWeek = "周三";
                break;
            case DateTimeConstants.THURSDAY:
                dayOfWeek = "周四";
                break;
            case DateTimeConstants.FRIDAY:
                dayOfWeek = "周五";
                break;
            case DateTimeConstants.SATURDAY:
                dayOfWeek = "周六";
            default:
                break;
        }
        return dayOfWeek;
    }


    //根据医院编号 和 科室编号 ，查询排班规则数据 副本
    @Override
    public Map<String, Object> getRuleSchedules(long page, long limit, String hoscode, String depcode) {
        //1 根据医院编号 和 科室编号 查询
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode);

        //2 根据工作日workDate期进行分组
        Aggregation agg = Aggregation.newAggregation(
                Aggregation.match(criteria),//匹配条件
                Aggregation.group("workDate")//分组字段
                        .first("workDate").as("workDate")
                        //3 统计号源数量
                        .count().as("docCount")
                        .sum("reservedNumber").as("reservedNumber")
                        .sum("availableNumber").as("availableNumber"),
                //排序
                Aggregation.sort(Sort.Direction.DESC, "workDate"),
                //4 实现分页
                Aggregation.skip((page - 1) * limit),
                Aggregation.limit(limit)
        );
        //调用方法，最终执行
        AggregationResults<BookingScheduleRuleVo> aggResults =
                mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = aggResults.getMappedResults();

        //分组查询的总记录数
        Aggregation totalAgg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")
        );
        AggregationResults<BookingScheduleRuleVo> totalAggResults =
                mongoTemplate.aggregate(totalAgg,
                        Schedule.class, BookingScheduleRuleVo.class);
        int total = totalAggResults.getMappedResults().size();

        //把日期对应星期获取
        for (BookingScheduleRuleVo bookingScheduleRuleVo : bookingScheduleRuleVoList) {
            Date workDate = bookingScheduleRuleVo.getWorkDate();
            String dayOfWeek = this.getDayOfWeek(new DateTime(workDate));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);
        }

        //设置最终数据，进行返回
        Map<String, Object> result = new HashMap<>();
        result.put("bookingScheduleRuleList", bookingScheduleRuleVoList);
        result.put("total", total);

        //获取医院名称
        String hosName = hospitalService.getHospNames(hoscode);
        //其他基础数据
        Map<String, String> baseMap = new HashMap<>();
        baseMap.put("hosname", hosName);
        result.put("baseMap", baseMap);

        return result;
    }


    /**
     * 根据日期获取周几数据
     *
     * @param
     * @return
     */
    /*

    private String getDayOfWeek(DateTime dateTime) {
        String dayOfWeek = "";
        switch (dateTime.getDayOfWeek()) {
            case DateTimeConstants.SUNDAY:
                dayOfWeek = "周日";
                break;
            case DateTimeConstants.MONDAY:
                dayOfWeek = "周一";
                break;
            case DateTimeConstants.TUESDAY:
                dayOfWeek = "周二";
                break;
            case DateTimeConstants.WEDNESDAY:
                dayOfWeek = "周三";
                break;
            case DateTimeConstants.THURSDAY:
                dayOfWeek = "周四";
                break;
            case DateTimeConstants.FRIDAY:
                dayOfWeek = "周五";
                break;
            case DateTimeConstants.SATURDAY:
                dayOfWeek = "周六";
            default:
                break;
        }
        return dayOfWeek;
    }

*/


    // 删除排班接口
    @Override
    public void remove(String hoscode, String hosScheduleId) {

        // 根据医院编号和排班的编号查询出医院的信息

        Schedule schedule = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(hoscode, hosScheduleId);
        if (null != schedule) {
            scheduleRepository.deleteById(schedule.getId());
        }

    }


    // 查询排班接口
    @Override
    public Page<Schedule> selectPage(int page, int limit, ScheduleQueryVo scheduleQueryVo) {

        // 创建配置 Pageable 对象，设置当前页和每页的记录数
        //0 是第一页 所有 page-1
        Pageable pageable = PageRequest.of(page - 1, limit);
        // 创建 Example 对象
        Schedule schedule = new Schedule();
        BeanUtils.copyProperties(scheduleQueryVo, schedule);

        // 设置一个值
        schedule.setIsDeleted(0);// 删除的标志

        ExampleMatcher resultMatcher = ExampleMatcher.matching().withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING).withIgnoreCase(true);

        Example<Schedule> example = Example.of(schedule, resultMatcher);

        Page<Schedule> schedulePage = scheduleRepository.findAll(example, pageable);

        return schedulePage;
    }


    // 上传排班接口
    @Override
    public void save(Map<String, Object> stringObjectMap) {

        // stringObjectMap 转换成 department 对象

        String toring = JSONObject.toJSONString(stringObjectMap);
// 转换
        Schedule schedule = JSONObject.parseObject(toring, Schedule.class);


        // 判断是否存在科室信息
        // 根据排班编号 和 科室编号查询
        Schedule scheduleSchedule = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(schedule.getHoscode(), schedule.getDepcode());

        // 判断
        if (scheduleSchedule != null) {
//copy不为null的值，该方法为自定义方法
            schedule.setUpdateTime(new Date());
            schedule.setIsDeleted(0);
            schedule.setStatus(1);// 状态
            scheduleRepository.save(scheduleSchedule);
        } else {
            schedule.setCreateTime(new Date());
            schedule.setUpdateTime(new Date());
            schedule.setIsDeleted(0);
            schedule.setStatus(1);// 状态
            scheduleRepository.save(schedule);

        }

    }


}
